<script setup>
    import {
        Management, Promotion, User, Crop, EditPen, SwitchButton, CaretBottom, School, Setting, Plus
    } from '@element-plus/icons-vue'
    import avatar from '@/assets/default.png'
    import {useRouter} from 'vue-router'
    import { ref, nextTick, computed } from 'vue'
    import {ElMessage, ElMessageBox} from 'element-plus'
    import adminApi from "@/api/admin.js";
    import {useAdminInfoStore} from "@/store/adminInfo.js";
    import {useTokenStore} from "@/store/token.js";
    import CoachCountEc from "@/components/CoachCountEc.vue";

    //条目被点击后,调用的函数
    const router = useRouter();
    const currentTitle = computed(() => {
        return router.getRoutes().find(item => item.path === router.currentRoute.value.path)?.meta?.title || '首页'
    })

    //加载发送请求
    const adminInfoStore = useAdminInfoStore();
    const tokenStore = useTokenStore();
    const admin = ref()
    const getUserInfo = () => {
        adminApi.adminInfo().then(result => {
            //数据存储在pinia中
            adminInfoStore.setAdminInfo(result.data)
            admin.value = result.data
        })
    }

    getUserInfo()

    //上传图片
    const handleAvatarSuccess = (result) => {
        admin.value.avatar = result.data
    }
    const headers = ref({
        Authorization: tokenStore.token
    })

    const info = () => {
        ElMessageBox.alert('基本资料', '基本资料', {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
            message: `
                <div style="width: 33vh;height: auto;margin-left: 30px;border-radius: 8px; border: 2px dashed #44cef6; padding: 12px; background: rgba(68,206,246,0.1)">
                    <div>
                        头像🙂：
                        <img src="`+ adminInfoStore.admin.avatar +`" style="width: 50px; border-radius:50%">
                    </div>
                    <div>
                        账户🪪：` + adminInfoStore.admin.name +`
                    </div>
                    <div>
                        电话☎️：` + adminInfoStore.admin.phone +`
                    </div>
                    <div>
                        邮箱📮：` + adminInfoStore.admin.email +`
                    </div>
                </div>
                `
        })
    }

    const handleCommand = (command) => {
        //判断指令
        switch (command) {
            case 'info':
                ElMessage.success('个人信息')
                info()
                break;
            case 'resetInfo':
                ElMessage.success('修改资料')
                resetInfo()
                break;
            case 'resetPassword':
                ElMessage.success('重置密码')
                resetPassword()
                break;
            case 'logout':
                ElMessageBox.confirm('您确定要退出登录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {
                    tokenStore.removeToken()
                    adminInfoStore.removeAdminInfo()
                    adminApi.logout().then(result => {
                        if (result.code === 0) {
                            ElMessage({
                                type: 'success',
                                message: result.msg
                            })
                            router.push('/login')
                        } else {
                            ElMessage.error(result.msg)
                        }
                    })
                })
                break;
            default:
                router.push('/admin/' + command)
                break;
        }
    }

    //更新个人资料
    //添加、编辑
    const dialogFormVisible = ref(false)
    const title = ref()

    const resetInfo = () => {
        dialogFormVisible.value = true
        title.value = '修改信息'
        adminApi.selectById(admin.value.id).then(result => {
            admin.value = result.data
        })
    }

    const update = () => {
        if (admin.value.id) {//编辑
            adminApi.update(admin.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success'})
                    dialogFormVisible.value = false
                    getUserInfo()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        } else {
            ElMessage.error('请先登录')
        }
    }

    //重置密码
    const adminResetDTO = ref({
        'id': '',
        'oldPassword': '',
        'newPassword': ''
    });
    const dialogResetPasswordDialog = ref(false)
    const resetForm = ref()
    //自定义确认密码的校验函数
    const rePasswordValid = (rule, value, callback) => {
        if (value == null || value === '') {
            return callback(new Error('请再次确认密码'))
        }
        //响应式对象要：registerData.value才能拿到值
        if (adminResetDTO.value.newPassword !== value) {
            return callback(new Error('两次输入密码不一致'))
        }
        callback()
    }
    const rules = ref({
        oldPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 3, max: 16, message: '密码长度必须为3~16位', trigger: 'blur'}
        ],
        newPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 3, max: 16, message: '密码长度必须为3~16位', trigger: 'blur'}
        ],
        reNewPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {validator: rePasswordValid, trigger: 'blur' }
        ]
    })

    const resetPassword = () => {
        dialogResetPasswordDialog.value = true
        adminResetDTO.value.id = admin.value.id
    }
    const reset = async (formEl) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                adminApi.resetPassword(adminResetDTO.value).then(result => {
                    if (result.code === 0) {
                        ElMessage.success(result.msg)
                        dialogResetPasswordDialog.value = false
                        tokenStore.removeToken();
                        adminInfoStore.removeAdminInfo();
                        // 跳转到登录
                        router.push('/login')
                    } else {
                        ElMessage.error(result.msg)
                    }
                })
            } else {
                ElMessage.error('表单验证失败');
            }
        })
    }
</script>

<template>
	<!-- element-plus中的容器 -->
	<el-container class="layout-container">
		<!-- 左侧菜单 -->
		<el-aside width="210px">
            <a href="/">
                <div class="el-aside__logo" style="height: 140px;"></div>
            </a>
			<!-- element-plus的菜单标签 -->
			<el-menu
                active-text-color="#ffd04b"
                background-color="#232323"
                text-color="#fff"
                router
                :default-openeds="['config-setting']"
            >
				<el-menu-item index="/course">
					<el-icon>
						<Management/>
					</el-icon>
					<span>课程管理</span>
				</el-menu-item>
                <el-menu-item index="/reserve">
                    <el-icon>
                        <Crop/>
                    </el-icon>
                    <span>预约管理</span>
                </el-menu-item>
                <el-menu-item index="/user">
                    <el-icon>
                        <User/>
                    </el-icon>
                    <span>用户管理</span>
                </el-menu-item>
                <el-menu-item index="/coach">
                    <el-icon>
                        <Crop/>
                    </el-icon>
                    <span>教练管理</span>
                </el-menu-item>
				<el-sub-menu index="config-setting">
					<template #title>
						<el-icon>
							<Setting/>
						</el-icon>
						<span>配置中心</span>
					</template>
					<el-menu-item index="/admin_role">
						<el-icon>
							<School/>
						</el-icon>
						<span>权限管理</span>
					</el-menu-item>
                    <el-menu-item index="/admin">
                        <el-icon>
                            <Promotion/>
                        </el-icon>
                        <span>管理员管理</span>
                    </el-menu-item>
                    <el-menu-item index="/role_permission">
                        <el-icon>
                            <School/>
                        </el-icon>
                        <span>权限管理</span>
                    </el-menu-item>
					<el-menu-item index="/log">
						<el-icon>
							<EditPen/>
						</el-icon>
						<span>日志记录</span>
					</el-menu-item>
				</el-sub-menu>
			</el-menu>
		</el-aside>
		<!-- 右侧主区域 -->
		<el-container>
			<!-- 头部区域 -->
			<el-header>
				<div><strong>健身房预约管理系统 - {{ currentTitle }}</strong></div>
				<!-- 下拉菜单 -->
				<!-- command: 条目被点击后会触发,在事件函数上可以声明一个参数,接收条目对应的指令 -->
				<el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                        <el-avatar :src="adminInfoStore.admin.avatar?adminInfoStore.admin.avatar:avatar"/>&nbsp;
                        <span class="el-dropdown__text">{{ adminInfoStore.admin.name }}</span>
                        <el-icon>
                            <CaretBottom/>
                        </el-icon>
                    </span>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
							<el-dropdown-item command="resetInfo" :icon="Crop">修改信息</el-dropdown-item>
							<el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
							<el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</el-header>
			<!-- 中间区域 -->
			<el-main>
				 <div style="width: 99%; height: auto;border: 1px solid blue;">
                     <el-breadcrumb
                         v-if="currentTitle === '首页'"
                     >
                         <div style="height: 500px; width: 50%; align-items: center;">
                             <CoachCountEc></CoachCountEc>
                         </div>
                     </el-breadcrumb>
                     <router-view></router-view>
                </div>
			</el-main>
			<!-- 底部区域 -->
			<el-footer>后台管理 ©2025 Created by Basil</el-footer>
		</el-container>
	</el-container>

    <!--编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" :lock-scroll="false">
        <el-form :model="admin">
            <el-form-item label="头像" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                >
                    <img v-if="admin.avatar" :src="admin.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            可以上传png/jpg/gif等格式的图片资源，且不超过5mb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="账号" :label-width="60">
                <el-input v-model="admin.name" autocomplete="off" :disabled="admin.id === 1"/>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="60">
                <el-input v-model="admin.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" :label-width="60">
                <el-input v-model="admin.phone" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="update">确认</el-button>
            </div>
        </template>
    </el-dialog>

    <!--重置密码-->
    <el-dialog v-model="dialogResetPasswordDialog" title="重置密码" width="500" :lock-scroll="false">
        <el-form ref="resetForm" :rules="rules" :model="adminResetDTO">
            <el-form-item prop="oldPassword" label="原密码" :label-width="100">
                <el-input v-model="adminResetDTO.oldPassword" autocomplete="off"/>
            </el-form-item>
            <el-form-item prop="newPassword" label="新密码" :label-width="100">
                <el-input v-model="adminResetDTO.newPassword" autocomplete="off"/>
            </el-form-item>
            <el-form-item prop="reNewPassword" label="重复新密码" :label-width="100">
                <el-input v-model="adminResetDTO.reNewPassword" autocomplete="off"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogResetPasswordDialog = false">取消</el-button>
                <el-button type="primary" @click="reset(resetForm)">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
    .layout-container {
        height: 100vh;

        .el-aside {
            background-color: #232323;

            &__logo {
                height: 120px;
                background: url('@/assets/logo.png') no-repeat center / 120px auto;
            }

            .el-menu {
                border-right: none;
            }
        }

        .el-header {
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .el-dropdown__box {
                display: flex;
                align-items: center;

                .el-icon {
                    color: #999;
                    margin-left: 10px;
                }

                &:active,
                &:focus {
                    outline: none;
                }
            }
        }

        .el-footer {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #666;
        }
    }

    .avatar-uploader {
        border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
        border: 2px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }

    .avatar{
        width: 178px;
        height: 178px;
        display: block;
    }
</style>